/*
* @Author: 窦子滨<zibin_5257@163.com>
* @Date: 2019-04-10 10:17
 */
package main

import (
	"HpTest/TcpPack"
	"HpTest/base"
	"net"
	"strings"
	"time"
)

var(
	//HpConn=conn.NewConn()
)

//打开socket连接监听
func SocketServer() {
	defer workerMain.Done()

	service := ":" + Config.Tcp.Listen
	tcpAddr, err := net.ResolveTCPAddr("tcp4", service)

	listener, err := net.ListenTCP("tcp", tcpAddr)

	base.Log.Info("充电桩调试工具TCP服务监听端口：" + Config.Tcp.Listen)

	if err != nil {
		base.Log.Error("打开socket TCP端口出错：" + err.Error())
		panic(err.Error())
		return
	}

	ip,err:=get_internal()

	if err!=nil{
		base.Log.Error("本机网卡ip获取错误（请自行确认本机ip地址）：" + err.Error())
	}else{
		base.Log.Info("本机网卡ip地址：%s",strings.Join(ip,","))
	}


	defer listener.Close()

	for {
		conn, err := listener.Accept()
		if err != nil {
			base.Log.Error("[][][建立tcp连接错误][%s]", err.Error())
			continue
		}

		//超时时间5分钟
		conn.SetDeadline(time.Now().Add(90 * time.Second))


		//开启连接处理
		go TcpPack.HandleConn(conn)
	}



}


func get_internal()([]string,error) {
	var ip []string
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return nil,err
	}
	for _, a := range addrs {
		if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				ip=append(ip,ipnet.IP.String())
			}
		}
	}
	return ip,nil
}